package com.zly.framework.rbac.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zly.framework.rbac.model.entity.Role;
import com.zly.framework.rbac.service.RoleService;
import com.zly.framework.rbac.vaildate.EntityInsert;
import com.zly.framework.rbac.vaildate.EntityUpdate;
import com.zly.framework.rbac.model.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/sys/role")
@RestController
@Tag(name = "角色接口")
public class RoleController {
    @Resource
    private RoleService roleServiceImpl;

    @Operation(summary = "分页获取角色", description = "分页获取角色")
    @GetMapping
    public Result<IPage<Role>> getByPage(@RequestParam Long current, @RequestParam Long size) {
        IPage<Role> rolePage = new Page<>(current, size);
        IPage<Role> page = roleServiceImpl.page(rolePage);
        return Result.SUCCESS(page);
    }

    @Operation(summary = "添加角色", description = "添加角色")
    @PostMapping
    public Result<Object> save(@Validated(value = {EntityInsert.class}) Role role) {
        roleServiceImpl.save(role);
        return Result.SUCCESS();
    }

    @Operation(summary = "修改角色", description = "修改角色")
    @PutMapping
    public Result<Object> updateRole(@Validated(value = {EntityUpdate.class}) Role role) {
        roleServiceImpl.updateById(role);
        return Result.SUCCESS();
    }

    @Operation(summary = "删除角色", description = "删除角色")
    @DeleteMapping
    public Result<Object> deleteRole(@RequestParam List<Long> roleIds) {
        // todo: 检查角色与用户和权限是否存在绑定关系
        roleServiceImpl.removeBatchByIds(roleIds);
        return Result.SUCCESS();
    }

    @Operation(summary = "分配权限", description = "分配权限")
    @PostMapping("/grantPermission")
    public Result<Object> grantPermission(@RequestParam("roleId") Long roleId,
                                          @RequestParam List<Long> permissionIds) {
        roleServiceImpl.grantPermission(roleId, permissionIds);
        return Result.SUCCESS();
    }
}
